var allBase = null;//项目
var pGuid = null;
var allCarrival = null;//堆放点
var alval = null;//堆放点--新增
var stackGuid = null;
var duifangPGuid = null;
// var allPicture = null;//图片
var allCArrivalRecord = null;//材料清单
var time = null;
// var wuzi = null;
var projectId = null;
var pguid = null;
var userall = null;
$(function () {
    $.when(
        getuserall(),
        $.get(baseURL+'csg/cpbase/select?ourid=isok',function (r) {
            allBase = r.returnlist;
            vm.allBase = allBase;
        }),
        $.get(baseURL+'csg/carrivalrecord/select',function (r) {
            allCarrival = r.returnlist;
            vm.allCarrival = allCarrival;
        }),
        // $.get(baseURL+'bss/dpicture/list',function (r) {
        //     allPicture = r.returnlist;
        //     vm.allPicture = allPicture;
        // }),
        $.get(baseURL+'csg/cgoodsdetail/select',function (r) {
            allCArrivalRecord = r.returnlist;
            vm.allCArrivalRecord = allCArrivalRecord;
        })
    ).done(

        $("#jqGrid1").jqGrid({
            url: baseURL +'csg/cpbase/list?state=isdelno&ourid=isok',
            datatype: "json",
            colModel: [
                { label: 'guid', name: 'guid', index: 'guid', width: 50, key: true,hidden: true  },

                { label: '项目名称', name: 'pBName', index: 'p_b_name', width: 200 },
                { label: '参与人', name: 'pBCollectid', index: 'p_b_collectid', width: 150 ,
                    formatter: function (cellvalue, options, rowObject) {
                        var names = "";


                        var ss = (cellvalue.replace(/\"/g, "").replace("[", "").replace("]", "") + "").split(",");
                        for (var i = 0; i < ss.length; i++) {

                            for (d in userall) {
                                if (ss[i] == userall[d].userId + "") {

                                    names += userall[d].username + ",";
                                }
                            }
                        }
                        if (names.length > 0) {
                            names = names.substring(0, names.length - 1);
                        }
                        return names;
                    }
                },

                { label: '创建时间', name: 'pBAddtime', index: 'p_b_addtime', width: 150,
                    formatter:function(value,options,row){
                        return value!=null?new Date(value).Format('yyyy-MM-dd hh:mm'):"";}
                }
            ],
            viewrecords: true,
            height: 500,

            rowNum: 10,
            rowList : [10,30,50],
            rownumbers: true,
            rownumWidth: 25,
            autowidth:true,
            multiselect: true,
            pager: "#jqGridPager1",
            jsonReader : {
                root: "page.list",
                page: "page.currPage",
                total: "page.totalPage",
                records: "page.totalCount"
            },
            prmNames : {
                page:"page",
                rows:"limit",
                order: "order"
            },
            gridComplete:function(){
                //隐藏grid底部滚动条
                $("#jqGrid1").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
            }
        }),

        $("#jqGrid").jqGrid({
            //后台已有限制条件
            url: baseURL + 'csg/carrivalrecord/list',
            datatype: "json",
            colModel: [
                { label: 'guid', name: 'guid', index: 'guid', width: 50, key: true,hidden:true },
                // { label: '最新图片', name: 'pServeraddress', index: 'p_serveraddress', width: 50,align: "center",hidden:true,
                //     sortable: false, editable: false,formatter: alarmFormatter
                //
                // },
                { label: '所属项目', name: 'pGuid', index: 'p_guid', width: 80,hidden:true,
                    formatter: function (cellvalue, options, rowObject) {
                        for (d in allBase) {
                            if (cellvalue == allBase[d].guid) return allBase[d].pBName;
                        }
                    }
                },
                { label: '堆放点', name: 'sPName', index: 's_p_name', width: 80 },
                /*{ label: '堆放点', name: 'sPGuid', index: 's_p_guid', width: 80,
                    formatter: function (cellvalue, options, rowObject) {
                        for (d in allCarrival) {
                            if (cellvalue == allCarrival[d].sPGuid) return allCarrival[d].sPName;
                        }
                    }
                },*/
                { label: '到货日期', name: 'aRTime', index: 'a_r_time', width: 80,
                    formatter:function(value,options,row){
                        return value!=null?new Date(value).Format('yyyy-MM-dd'):"";
                    }
                },//材料表中的属性。。
                // { label: '到货清单', name: 'sPqingdan', index: 's_p_name', width: 80 },
                { label: '到货物资', name: 'guid', index: 'guid', width: 80,
                    formatter: function (cellvalue, options, rowObject) {
                        for (d in allCArrivalRecord) {
                            if (cellvalue == allCArrivalRecord[d].aRGuid) return allCArrivalRecord[d].gDBigtype;
                        }
                    }
                },
                { label: '到货数量', name: 'guid', index: 'guid', width: 80,
                    formatter: function (cellvalue, options, rowObject) {
                        for (d in allCArrivalRecord) {
                            if (cellvalue == allCArrivalRecord[d].aRGuid) return allCArrivalRecord[d].gDNum;
                        }
                    }
                },
                { label: '记录人id', name: 'aRUser', index: 'a_r_user', width: 80,hidden:true },
                { label: '记录人名称', name: 'aRUsername', index: 'a_r_username', width: 80 },
                { label: '状态', name: 'aRDatastate', index: 'a_r_datastate', width: 80,hidden:true },
                { label: '操作', name: '', width: 100,
                    formatter: function (cellvalue, options, rowObject) {
                        return "<a  class='btn btn-primary' onclick='showArrivalRecord(\"" + rowObject.guid + "\")' >&nbsp;详情</a>"
                    }
                }
            ],
            viewrecords: true,
            height: 385,
            rowNum: 10,
            rowList : [10,30,50],
            rownumbers: true,
            rownumWidth: 25,
            autowidth:true,
            multiselect: true,
            pager: "#jqGridPager",
            jsonReader : {
                root: "page.list",
                page: "page.currPage",
                total: "page.totalPage",
                records: "page.totalCount"
            },
            prmNames : {
                page:"page",
                rows:"limit",
                order: "order",
                addoper:"add"
            },
            gridComplete:function(){

                $('#jqGrid img').click(function (e) {
                    var _this = $(this);//将当前的pimg元素作为_this传入函数
                    imgShow("#outerdiv", "#innerdiv", "#bigimg", _this);
                });

                //隐藏grid底部滚动条
                $("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
            }
        })
    )
});


function  getuserall()
{
    $.get(baseURL + "sys/user/select" , function (r) {
        userall = r.returnlist;

    });
    vm.userall=userall;

}



/**
 * 	项目--对应堆放点
 */
/*function getPro() {
    //获取所选项目的guid
    projectId = $("#projectId").val();

    //根据项目ID获取所属堆放点
    var url = baseURL+'csg/cstackpoint/select?pGuid='+projectId;

    $.get(url, function (data) {
        var allCStackPoint = data.returnlist;
        if (allCStackPoint) {
            $("#cArrivalId").empty();
            var h = "<option value=''>---请选择---</option>";
            for (var i = 0; i < allCStackPoint.length; i++) {
                h += "<option value='" + allCStackPoint[i]['guid'] + "'>" + allCStackPoint[i]['sPName'] + "</option>"

            }
            $("#cArrivalId").html(h);
        }
    }, "json");
}*/

/*function ads() {
    projectId = $("#projectId").val();
    console.log("add="+projectId);
    $.get(baseURL+'csg/cstackpoint/select?pGuid='+projectId,function (r) {
        alval = r.returnlist;
        vm.alval = alval;
    })

}*/


function imgShow(outerdiv, innerdiv, bigimg, _this){
    var src = _this.attr("src");//获取当前点击的pimg元素中的src属性
    $(bigimg).attr("src", src);//设置#bigimg元素的src属性

    /*获取当前点击图片的真实大小，并显示弹出层及大图*/
    $("<img/>").attr("src", src).load(function(){
        var windowW = $(window).width();//获取当前窗口宽度
        var windowH = $(window).height();//获取当前窗口高度
        var realWidth = this.width;//获取图片真实宽度
        var realHeight = this.height;//获取图片真实高度
        var imgWidth, imgHeight;
        var scale = 0.8;//缩放尺寸，当图片真实宽度和高度大于窗口宽度和高度时进行缩放

        if(realHeight>windowH*scale) {//判断图片高度
            imgHeight = windowH*scale;//如大于窗口高度，图片高度进行缩放
            imgWidth = imgHeight/realHeight*realWidth;//等比例缩放宽度
            if(imgWidth>windowW*scale) {//如宽度扔大于窗口宽度
                imgWidth = windowW*scale;//再对宽度进行缩放
            }
        } else if(realWidth>windowW*scale) {//如图片高度合适，判断图片宽度
            imgWidth = windowW*scale;//如大于窗口宽度，图片宽度进行缩放
            imgHeight = imgWidth/realWidth*realHeight;//等比例缩放高度
        } else {//如果图片真实高度和宽度都符合要求，高宽不变
            imgWidth = realWidth;
            imgHeight = realHeight;
        }
        $(bigimg).css("width",imgWidth);//以最终的宽度对图片缩放

        var w = (windowW-imgWidth)/2;//计算图片与窗口左边距
        var h = (windowH-imgHeight)/2;//计算图片与窗口上边距
        $(innerdiv).css({"top":h, "left":w});//设置#innerdiv的top和left属性
        $(outerdiv).fadeIn("fast");//淡入显示#outerdiv及.pimg
    });

    $(outerdiv).click(function(){//再次点击淡出消失弹出层
        $(this).fadeOut("fast");
    });
}
function alarmFormatter(cellvalue, options, rowdata) {
    return ' <img  src="' +baseURL+'rest/photo/queryPic?address='+ cellvalue + '"  id="img' + rowdata.guid + '"  style="width:40px;height:40px;" />';
}

/**
 *  堆放点
 */
/*function getProject() {
    //获取所选项目的guid
    stackGuid = $("#projectIdquer").val();

    //根据项目ID获取所属堆放点
    var url = baseURL+'csg/cstackpoint/select?pGuid='+stackGuid;

    $.get(url, function (data) {
        var allCStackPoint = data.returnlist;
        if (allCStackPoint) {
            $("#cArrivalIdquer").empty();
            var h = "<option value=''>全部</option>";
            for (var i = 0; i < allCStackPoint.length; i++) {
                h += "<option value='" + allCStackPoint[i]['guid'] + "'>" + allCStackPoint[i]['sPName'] + "</option>"
                stackGuid = allCStackPoint[i]['guid'];
            }
            $("#cArrivalIdquer").html(h);
        }
    }, "json");

}*/



/*function getProjectss() {
    //获取所选项目的guid
    duifangPGuid = $("#cArrivalIdquer").val();

    //根据项目ID获取所属堆放点
    /!*var url = baseURL+'csg/cstackpoint/select?pGuid='+stackGuid;

     $.get(url, function (data) {
     var allCStackPoint = data.returnlist;
     if (allCStackPoint) {
     $("#cArrivalIdquer").empty();
     var h = "<option value=''>---请选择---</option>";
     for (var i = 0; i < allCStackPoint.length; i++) {
     h += "<option value='" + allCStackPoint[i]['guid'] + "'>" + allCStackPoint[i]['sPName'] + "</option>"
     }
     $("#cArrivalIdquer").html(h);
     }
     }, "json");*!/
}*/


/**
 *  物资清单
 * @param guid
 */
function showArrivalRecord(guid) {
    var title ="物资清单";
    var pGuid = vm.q.pGuid;
    var content = "cmiddlegoodsNewdetail.html?guid=" + guid+"&pGuid="+pGuid;
    layer.open({
        type: 2,
        title: title,
        shadeClose: true,
        shade: 0.5,
        maxmin: true, //开启最大化最小化按钮
        area: ['95%', '95%'],
        content: content

    });
}

/**
 *  项目物资汇总
 */
function exportCArrival() {
    //获取所选项目的guid
    // stackGuid = $("#projectIdquer").val();
    var pGuid = vm.q.pGuid;
    var re_records = $("#jqGrid").jqGrid('getGridParam', 'records'); //获取数据总条数
    if(pGuid == null){
        alert("请选择项目")
        return ;
    }
    if(re_records==0){
        alert("该项目无数据，请核对后操作");
        return;
    }
    location.href=baseURL + "csg/carrivalrecord/exports?pGuid="+pGuid;
}


/**
 *  项目详情导出
 */
function exportImgss(){
    // stackGuid = $("#projectIdquer").val();
    var pGuid = vm.q.pGuid;
    var re_records = $("#jqGrid").jqGrid('getGridParam', 'records'); //获取数据总条数
    if(pGuid == null){
        alert("请选择项目")
        return ;
    }
    if(re_records==0){
        alert("该项目无数据，请核对后操作");
        return;
    }
    location.href=baseURL + "csg/carrivalrecord/exportsimg?pGuid="+pGuid;
}

var vm = new Vue({
    el:'#rrapp',
    data:{
        showList: true,
        stackGuid:null,
        userall:userall,
        q:{
            psname:null,
            ppppBName:null,
            pGuid:null,
            stack:null
        },
        // duifangPGuid:duifangPGuid,
        // sPGuid:sPGuid,
        title: null,
        time:time,
        // wuzi:wuzi,
        allBase:allBase,
        // allPicture:allPicture,
        allCarrival:allCarrival,
        alval:alval,
        allCArrivalRecord:allCArrivalRecord,
        // pGuid:pGuid,
        cArrivalRecord: {},
        stackPoint: {}
    },
    methods: {
        query: function () {
            vm.reload();
        },

        add: function(){
            vm.showList = false;
            vm.title = "新增";

            vm.cArrivalRecord = {};
        },
        update: function (event) {
            var guid = getSelectedRow();
            if(guid == null){
                return ;
            }

            var rowData = $("#jqGrid").jqGrid('getRowData',guid);
            var pname = rowData.pGuid;
            $.get(baseURL + "csg/cpbase/select?pname="+pname, function(r) {
                pguid=r.returnlist[0].guid;

                $.get(baseURL + "csg/cpbase/info/"+pguid, function(r) {
                    if (r.cPBase.pBState == 30) {
                        alert("项目已归档，无法修改材料到货信息！");
                    }else{
                        vm.showList = false;
                        vm.title = "修改";

                        vm.getInfo(guid)
                    }
                });

            });


        },
        saveOrUpdate: function (event) {


            var sPGuid = vm.allCarrival.guid;
            var pGuid = vm.pGuid;


            var	url = vm.cArrivalRecord.guid == null ? "csg/carrivalrecord/saveNew/"+sPGuid+"/"+pGuid : "csg/carrivalrecord/update";

            $.ajax({
                type: "POST",
                url: baseURL + url,
                contentType: "application/json",
                data: JSON.stringify(vm.cArrivalRecord),
                success: function(r){
                    if(r.code === 0){
                        alert('操作成功', function(index){
                            vm.reload();
                            console.log("carrival===刷新成功！")
                            // location.reload();
                        });
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        del: function (event) {
            var guids = getSelectedRows();
            if(guids == null){
                return ;
            }

            var guid=guids[0];

            var rowData = $("#jqGrid").jqGrid('getRowData',guid);
            var pname = rowData.pGuid;
            $.get(baseURL + "csg/cpbase/select?pname="+pname, function(r) {
                pguid=r.returnlist[0].guid;

                $.get(baseURL + "csg/cpbase/info/"+pguid, function(r) {
                    console.log("r="+JSON.stringify(r))
                    if (r.cPBase.pBState != 30) {
                        confirm('确定要删除选中的记录？', function(){
                            $.ajax({
                                type: "POST",
                                url: baseURL + "csg/carrivalrecord/delete",
                                contentType: "application/json",
                                data: JSON.stringify(guids),
                                success: function(r){
                                    if(r.code == 0){
                                        alert('操作成功', function(index){
                                            $("#jqGrid").trigger("reloadGrid");
                                        });
                                    }else{
                                        alert(r.msg);
                                    }
                                }
                            });
                        });
                    }else{
                        alert("项目已归档，无法删除材料到货信息！")
                    }
                })
            });


        },
        getInfo: function(guid){
            $.get(baseURL + "csg/carrivalrecord/info/"+guid, function(r){
                vm.cArrivalRecord = r.cArrivalRecord;
                vm.cArrivalRecord.aRTime = r.cArrivalRecord.aRTime!=null?new Date().Format("yyyy-MM-dd"):"";
            });
        },
        showprolist:function (event) {

            // vm.q.pGuid='b6400318-7a6f-4de5-92e8-ddec55f10394';
            layer.open({
                type: 1,
                offset: '50px',
                skin: 'layui-layer-molv',
                title: "选择项目",
                area: ['700px', '460px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#deptLayermy"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var grid = $("#jqGrid1");
                    var rowKey = grid.getGridParam("selrow");
                    if (!rowKey) {
                        alert("请选择一条记录");
                        return;
                    }

                    var selectedIDs = grid.getGridParam("selarrrow");
                    if (selectedIDs.length > 1) {
                        alert("只能选择一条记录");
                        return;
                    }
                    vm.getStackPoint(selectedIDs[0]);
                    vm.q.pGuid=selectedIDs[0];

                    for (d in  allBase) {
                        if (allBase[d].guid == selectedIDs[0]) {
                            vm.q.psname=allBase[d].pBName;
                        }
                    }
                    layer.close(index);

                }
            });


        },
        getStackPoint: function (guid) {
            console.log(guid)

            /*for (d in  allBase) {
                if (allBase[d].guid == guid) {

                    if (allBase[d].pBType == '100')
                        vm.pType = type1;
                    else
                        vm.pType = type2;
                }
            }*/
            // console.log("aaaa"+vm.pType);
            $.get(baseURL + "csg/cstackpoint/select/" + guid, function (r) {
                // console.log(r);
                vm.stackPoint = r.returnlist;
                // console.log(vm.stackPoint);
            });

        },
        reload: function (event) {
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam','page');
            $("#jqGrid").jqGrid('setGridParam',{
                postData:{
                    "pGuid":vm.q.pGuid,
                    "stack":vm.q.stack,
                    // "duifangPGuid":duifangPGuid,
                    // "allPicture":vm.allPicture,
                    "time":vm.time
                },
                page:page
            }).trigger("reloadGrid");
        },
        reloadpro: function (event) {
            var page = $("#jqGrid1").jqGrid('getGridParam','page');
            $("#jqGrid1").jqGrid('setGridParam',{
                postData:{
                    'pBName': vm.q.ppppBName,
                },
                page:page
            }).trigger("reloadGrid");
        }
    }
});